<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Shop\Service;

use Admin\Data\Common;
use Doctrine\ORM\EntityManager;
use Laminas\Session\Container;
use User\Entity\User;
use User\Entity\UserGroup;

class ShopUserManager
{
    const USER_ALREADY_LOGIN = 1;   //已经登录
    const USER_NOT_LOGIN     = -1;  //未登录

    private $entityManager;
    private $sessionUser;

    public function __construct(
        EntityManager $entityManager
    )
    {
        $this->entityManager    = $entityManager;
        $this->sessionUser      = new Container('dbshopUser');
    }

    /**
     * 会员注册处理
     * @param array $data
     * @return User
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function userRegister(array $data)
    {
        $userGroupId    = Common::configValue('default_user_group_id', 'customer');
        $userGroupInfo  = $this->entityManager->getRepository(UserGroup::class)->findOneByUserGroupId($userGroupId);

        $userRegisterAudit = Common::configValue('user_register_audit', 'customer');

        $user = new User();
        $user->valuesSet($data);
        $user->setUserGroupId($userGroupId);
        $user->setUserMoney(0.00);
        $user->setIntegralType1Num(0);
        $user->setIntegralType2Num(0);
        $user->setUserAddTime(time());
        $user->setUserStatus($userRegisterAudit == 'no' ? 1 : 3);
        $user->setOneUserGroup($userGroupInfo);

        $this->entityManager->persist($user);
        $this->entityManager->flush();

        if($userRegisterAudit == 'no') $this->userLoginSession($user);

        return $user;
    }

    /**
     * 会员登录处理
     * @param array $data
     * @return int
     */
    public function userLogin(array $data)
    {
        $userInfo = $this->entityManager->getRepository(User::class)->findUserLogin($data['loginAccount']);

        //相关的状态验证，已经在提交的过程中进行了验证
        if ($userInfo && Common::verifyUserPassword($data['loginPassword'], $userInfo->getUserPassword())) {
            $this->userLoginSession($userInfo);
            return $userInfo;
        }

        return self::USER_NOT_LOGIN;
    }

    /**
     * 会员退出
     * @return int
     */
    public function userLogout()
    {
        if($this->sessionUser->offsetGet('user_id') <= 0) return self::USER_NOT_LOGIN;
        $this->sessionUser->getManager()->getStorage()->clear($this->sessionUser->getName());
        return self::USER_ALREADY_LOGIN;
    }

    /**
     * 编辑客户状态
     * @param $userStatus
     * @param $userId
     * @return int|mixed|string
     */
    public function updateUserStatus($userStatus, $userId)
    {
        $qb = $this->entityManager->createQueryBuilder();
        $qb->update(User::class, 'u')->set('u.userStatus', ':userStatus')->setParameter('userStatus', $userStatus)
            ->where('u.userId = :userId')->setParameter('userId', $userId);

        return $qb->getQuery()->execute();
    }

    /**
     * 编辑邮件验证码
     * @param $emailAuditCode
     * @param $userId
     * @return int|mixed|string
     */
    public function updateUserEmailAuditCode($emailAuditCode, $userId)
    {
        $qb = $this->entityManager->createQueryBuilder();
        $qb->update(User::class, 'u')->set('u.userEmailAuditCode', ':userEmailAuditCode')->setParameter('userEmailAuditCode', $emailAuditCode)
            ->where('u.userId = :userId')->setParameter('userId', $userId);

        return $qb->getQuery()->execute();
    }

    /**
     * 编辑会员积分
     * @param array $data
     * @param $userId
     * @return int|mixed|string
     */
    public function updateUserUserIntegral(array $data, $userId)
    {
        $qb = $this->entityManager->createQueryBuilder();
        $qb->update(User::class, 'u');
        if(isset($data['integralType1Num'])) $qb->set('u.integralType1Num', ':integralType1Num')->setParameter('integralType1Num', intval($data['integralType1Num']));
        if(isset($data['integralType2Num'])) $qb->set('u.integralType2Num', ':integralType2Num')->setParameter('integralType2Num', intval($data['integralType2Num']));
        $qb->where('u.userId = :userId')->setParameter('userId', $userId);

        return $qb->getQuery()->execute();
    }

    /**
     * 编辑密码修改字符串
     * @param $editCode
     * @param $userId
     * @return int|mixed|string
     */
    public function updateUserForgotPasswordCode($editCode, $userId)
    {
        $qb = $this->entityManager->createQueryBuilder();
        $qb->update(User::class, 'u')->set('u.userForgotPasswordCode', ':editCode')->setParameter('editCode', $editCode)
            ->where('u.userId = :userId')->setParameter('userId', $userId);

        return $qb->getQuery()->execute();
    }

    /**
     * 密码重置
     * @param $password
     * @param $userId
     * @return int|mixed|string
     */
    public function resetUserPassword($password, $userId)
    {
        $qb = $this->entityManager->createQueryBuilder();
        $qb->update(User::class, 'u')->set('u.userPassword', ':userPassword')->setParameter('userPassword', Common::createUserPassword($password))
            ->set('u.userForgotPasswordCode', ':userForgotPasswordCode')->setParameter('userForgotPasswordCode', '')
            ->where('u.userId = :userId')->setParameter('userId', $userId);

        return $qb->getQuery()->execute();
    }

    /**
     * 检查客户状态及信息
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function checkUser()
    {
        $userInfo = $this->entityManager->getRepository(User::class)->findOneBy(['userId' => $this->sessionUser->offsetGet('user_id'), 'userStatus' => 1]);
        if ($userInfo == null) {
            $this->sessionUser->getManager()->getStorage()->clear($this->sessionUser->getName());
        } else {
            $integralUserGroup = Common::checkIntegralUserGroup($userInfo->getUserGroupId(), $userInfo->getOneUserGroup()->getUserGroupName(), $userInfo->getIntegralType2Num());
            if ($integralUserGroup['userGroupId'] != $this->sessionUser->offsetGet('user_group_id')) {//判断如果等级在积分范围内，客户等级是否与现有登录客户等级是否相同
                $this->sessionUser->offsetSet('user_group_id', $integralUserGroup['userGroupId']);
                $this->sessionUser->offsetSet('user_group_name', $integralUserGroup['userGroupName']);
                if ($integralUserGroup['userGroupId'] != $userInfo->getUserGroupId()) {//积分等级跟目前的客户等级不相同
                    $userInfo->valuesSet(['userGroupId' => $integralUserGroup['userGroupId']]);
                    $this->entityManager->flush();
                }
            }
        }
    }

    /**
     * 设置登录session
     * @param User $user
     */
    public function userLoginSession(User $user)
    {
        $this->sessionUser->offsetSet('user_id', $user->getUserId());
        $this->sessionUser->offsetSet('user_name', $user->getUserName());
        $this->sessionUser->offsetSet('user_group_id', $user->getOneUserGroup()->getUserGroupId());
        $this->sessionUser->offsetSet('user_group_name', $user->getOneUserGroup()->getUserGroupName());
    }
}